//
//  HttpConnectionUtil.m
//  Surfing_Platform
//
//  Created by amei on 12-4-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "HttpConnectionUtil.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <netdb.h>
#import <SystemConfiguration/SCNetworkReachability.h>
#import "Reachability.h"

@implementation HttpConnectionUtil
@synthesize mConnection;
@synthesize mReceiveData;
@synthesize mResponseData;
@synthesize mDelegate;

-(id)initWithDelegate:(id<HttpConnectionDelegate>)delegate{
    self = [self init];
    if(self != nil){
        self.mDelegate = delegate;
    }
    return self;
}
-(BOOL) NetworkAvisible{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        return NO;
    }
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable && !needsConnection) ? YES : NO;
}
- (BOOL) connectedToNetwork:(NSString*)url
{
    BOOL result = NO;
    
    Reachability *r = [Reachability reachabilityWithHostName:url];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            result = NO;
            break;
        case ReachableViaWWAN:
            result = YES;
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
            result = YES;
            break;
    }
    NSLog(@"network status = %d",[r currentReachabilityStatus]);
    return result;
}
-(void)asyncConnect:(NSString *)url AndMethod:(int)method MutableData:(NSMutableData *)data{
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    if(HTTP_REQUEST_GET == method){
        [urlRequest setHTTPMethod:@"GET"];
    }else if(HTTP_REQUEST_POST == method){
        [urlRequest setHTTPMethod:@"POST"];
    }
    if(data != nil){
        [urlRequest setHTTPBody:data];
    }
    self.mConnection = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
    
    //show connection the network is visible in the status bar
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
-(void)syncConnect:(NSString *)url AndMethod:(int)method MutableData:(NSMutableData *)data{
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    if(HTTP_REQUEST_GET == method){
        [urlRequest setHTTPMethod:@"GET"];
    }else if(HTTP_REQUEST_POST == method){
        [urlRequest setHTTPMethod:@"POST"];
    }
    if(data != nil){
        [urlRequest setHTTPBody:data];
    }
    NSData *returnData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil]; 
    
    mResponseData = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
    NSLog(@"syncConnect   %@",mResponseData);
    
    [mDelegate ReponseCallBack:mResponseData];
    [urlRequest release];
}

#pragma mark -
#pragma mark NSURLConnection delegate methods
// -------------------------------------------------------------------------------
//    handleError:error
// -------------------------------------------------------------------------------
- (void)handleError:(NSError *)error
{
    
    NSString *errorstr = [[NSString alloc]initWithFormat:@"error : %@",error];
    NSLog(@"%@",errorstr);
    [mDelegate ReponseCallBack:@"failed"];
}
// -------------------------------------------------------------------------------
//    connection:didReceiveResponse:response
// -------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.mReceiveData = [NSMutableData data];    // start off with new data
}
// -------------------------------------------------------------------------------
//    connection:didReceiveData:data
// -------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [mReceiveData appendData:data];  // append incoming data
}
// -------------------------------------------------------------------------------
//    connection:didFailWithError:error
// -------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    if ([error code] == kCFURLErrorNotConnectedToInternet)
    {
        // if we can identify the error, we can present a more precise message to the user.
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"No Connection Error"
                                                             forKey:NSLocalizedDescriptionKey];
        NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
                                                         code:kCFURLErrorNotConnectedToInternet
                                                     userInfo:userInfo];
        [self handleError:noConnectionError];
    }
    else
    {
        // otherwise handle the error generically
        [self handleError:error];
    }
    
    self.mConnection = nil;   // release our connection
}

// -------------------------------------------------------------------------------
//    connectionDidFinishLoading:connection
// -------------------------------------------------------------------------------
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.mConnection = nil;   // release our connection
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;   
    
    mResponseData = [[NSString alloc] initWithData:mReceiveData encoding:NSUTF8StringEncoding];
    NSLog(@"asyncConnect  %@",mResponseData);
    
    [mDelegate ReponseCallBack:mResponseData];
    
    self.mReceiveData = nil;
}

-(void)dealloc{
    [mConnection release];
    [mReceiveData release];
    [mResponseData release];
    
    [super dealloc];
}

@end
